<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { useLocale } from '@/locale/locale';
import { useRouter } from '@/router';
import { useAuthStore } from '@/store/auth';
import { getNavbarHeight } from '@/utils/navbar';
import { isWechat } from '@/utils/platform';
import { rpx2px } from '@/utils/px';
import LoginWithEmail from './components/login-with-email.vue';
import LoginWithPhone from './components/login-with-phone.vue';
import LoginWithWechatBoundPhone from './components/login-with-wechat-bound-phone.vue';

const { t } = useLocale();
const authStore = useAuthStore();
const router = useRouter();

const settings = reactive({
  color: '#fff',
  background: 'transparent'
});

async function handleLogin(data: any) {
  if (!authStore.isAgreementAccepted) {
    return uni.showToast({
      icon: 'none',
      title: t('LLKey_readAgree')
    });
  }

  if (authStore.isWechatMode) {
    authStore.WxLoginGetOpenId(data.code);
  } else {
    authStore.loginWithVerificationCode();
  }
}

const paddingTop = ref(rpx2px(280));
const paddingBottom = ref(rpx2px(60));

onMounted(() => {
  if (!isWechat()) {
    paddingTop.value = paddingTop.value - getNavbarHeight();
    document.title = t('LLKey_login');
  }
});
</script>

<template>
  <uni-nav-bar
    v-if="isWechat()"
    :background-color="settings.background"
    :color="settings.color"
    :border="false"
    fixed
    status-bar
    left-icon="left"
    @click-left="router.back()"
  />

  <view class="absolute top-0 left-0 right-0">
    <image
      src="https://apt11-1251002327.cos.ap-tokyo.myqcloud.com/miniapp/user_and_login_top_bg.png"
      :style="{
        width: `${rpx2px(750)}px`,
        height: `${rpx2px(660)}px`,
        objectFit: 'cover'
      }"
    />
    <view
      class="absolute top-0 left-0 right-0"
      :style="`padding: ${paddingTop}px ${paddingBottom}px 0`"
    >
      <view class="mb-2 text-xxl text-primary">{{ t('LLKey_welcome') }}</view>
      <view class="text-base text-fourth" style="margin-bottom: 200rpx">
        {{ t('LLKey_description') }}
      </view>
      <template v-if="isWechat()">
        <LoginWithPhone
          v-if="authStore.isPhoneMode"
          @login="handleLogin"
          @switch="authStore.setModeToWechat"
        />
        <LoginWithWechatBoundPhone
          v-if="authStore.isWechatMode"
          @login="handleLogin"
          @switch="authStore.setModeToPhone"
        />
      </template>
      <template v-else>
        <LoginWithPhone
          v-if="authStore.isPhoneMode"
          @login="handleLogin"
          @switch="authStore.setModeToEmail"
        />
        <LoginWithEmail
          v-if="authStore.isEmailMode"
          @login="handleLogin"
          @switch="authStore.setModeToPhone"
        />
      </template>
    </view>
  </view>
</template>
